<template>
  <div class="app-container">
    <el-card style="margin-bottom: 10px;">
      <el-descriptions :column="5" border :colon="false" :label-style="{ width: '40px' }">
        <template #title>
          <div class="card-title"><span>料箱 ESD 信息的统计数据</span></div>
        </template>
        <el-descriptions-item label-align="center">
          <template #label><span class="card-content">正常数量</span></template><div style="align-items: center;" class="card-content">{{ headInfo.normalCount }}</div>
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label><span class="card-content">临期数量</span></template><div style="align-items: center;" class="card-content">{{ headInfo.nearExpiryCount }}</div>
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label><span class="card-content">过期数量</span></template><div style="align-items: center;" class="card-content">{{ headInfo.expiredCount }}</div>
        </el-descriptions-item>
        <el-descriptions-item label-align="center">
          <template #label><span class="card-content">总数量</span></template><div style="align-items: center;" class="card-content">{{ headInfo.totalCount }}</div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 扫码功能区域 -->
    <el-card style="margin-bottom: 10px;">
      <div class="scan-area">
        <el-form :model="scanForm" inline>
          <el-form-item label="料箱码" prop="containerCode">
            <el-input
              v-model.trim="scanForm.containerCode"
              placeholder="请输入料箱码"
              clearable
              style="width: 200px"
            />
            <el-button style="margin-left: 5px;" type="primary" icon="Search" @click="handleScanBox">扫描料箱</el-button>
          </el-form-item>
          
          <!-- 扫码结果展示区域 -->
          <el-descriptions v-if="showScanResult" column="1" border style="margin-top: 10px; width: 100%" >
            <template #title>
              <div class="scan-result-title">料箱ESD绑定信息</div>
            </template>
            <el-descriptions-item label="料箱编号">{{ boxEsdStatus.containerId }}</el-descriptions-item>
            <el-descriptions-item label="绑定状态">{{ boxEsdStatus.hasBinding ? '已绑定' : '未绑定' }}</el-descriptions-item>
            
            <!-- 已绑定状态显示的信息 -->
            <template v-if="boxEsdStatus.hasBinding">
              <el-descriptions-item label="ESD编码">{{ boxEsdStatus.esdCode }}</el-descriptions-item>
              <el-descriptions-item label="绑定日期">{{ parseTime(boxEsdStatus.bindDate) }}</el-descriptions-item>
              <el-descriptions-item label="到期日期">{{ parseTime(boxEsdStatus.expiryDate) }}</el-descriptions-item>
              <el-descriptions-item label="剩余天数">{{ boxEsdStatus.remainingDays }}</el-descriptions-item>
              <el-descriptions-item label="ESD状态">
                <span :class="boxEsdStatus.esdStatus === '已过期' ? 'status-expired' : 'status-normal'">
                  {{ boxEsdStatus.esdStatus }}
                </span>
              </el-descriptions-item>
            </template>
          </el-descriptions>
          
          <!-- 操作按钮区域 -->
          <div v-if="showScanResult" class="scan-operation" style="margin-top: 10px;">
            <el-input
              v-model.trim="scanForm.esdCode"
              placeholder="请输入ESD码"
              clearable
              style="width: 200px; margin-right: 10px"
              v-if="!boxEsdStatus.hasBinding || showUpdateInput"
            />
            <el-button 
              type="success" 
              icon="Link" 
              @click="handleBindEsd"
              v-if="!boxEsdStatus.hasBinding"
            >
              前往绑定
            </el-button>
            <el-button 
              type="warning" 
              icon="RefreshLeft" 
              @click="showUpdateInput = true"
              v-if="boxEsdStatus.hasBinding && !showUpdateInput"
            >
              更新绑定
            </el-button>
            <el-button 
              type="primary" 
              icon="Check" 
              @click="handleUpdateBind"
              v-if="showUpdateInput"
            >
              确认更新
            </el-button>
            <el-button 
              type="info" 
              icon="Close" 
              @click="resetScan"
              v-if="showScanResult"
            >
              重置
            </el-button>
          </div>
        </el-form>
      </div>
    </el-card>

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="120px" @submit.prevent>
      <el-form-item label="料箱编号" prop="containerId">
        <el-input
          v-model.trim="queryParams.containerId"
          placeholder="请输入料箱编号"
          clearable
          @keyup.enter="handleQuery"
          style="width: 195px"
        />
      </el-form-item>
      <el-form-item label="ESD 条码" prop="esdCode">
        <el-input
          v-model.trim="queryParams.esdCode"
          placeholder="请输入 ESD 条码"
          clearable
          @keyup.enter="handleQuery"
          style="width: 195px"
        />
      </el-form-item>
      <el-form-item label="有效周期" prop="esdValidPeriod">
        <el-input
          v-model.trim="queryParams.esdValidPeriod"
          placeholder="请输入有效周期"
          clearable
          @keyup.enter="handleQuery"
          style="width: 195px"
        />
      </el-form-item>
      <el-form-item label="ESD 条码状态" prop="esdStatus">
        <el-select
          v-model="queryParams.esdStatus"
          placeholder="请选择 ESD 条码状态"
          clearable
          style="width: 195px"
          @change="handleQuery"          
        >
          <el-option
            v-for="dict in esd_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="有效期单位" prop="validPeriodUnit">
        <el-select
          v-model="queryParams.validPeriodUnit"
          placeholder="请选择有效期单位"
          clearable
          style="width: 195px"
        >
          <el-option
            v-for="dict in valid_period_unit"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="ESD绑定日期" prop="esdBindDate">
        <el-date-picker clearable
          v-model="queryParams.esdBindDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择ESD绑定日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="禁用状态" prop="disableStatus">
        <el-select
          v-model="queryParams.disableStatus"
          placeholder="请选择禁用状态"
          clearable
          style="width: 195px"
        >
          <el-option
            v-for="dict in esd_disabled_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:esd:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="multiple"
          icon="Plus"
          @click="batchAddButton"
        >批量新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:esd:edit']"
        >修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:esd:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:esd:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Download"
          @click="downloadTemplate"
        >下载导入模板</el-button>
      </el-col>
      <el-col :span="1.5">
        <MyUpload
          buttonName="导入 ESD 信息"
          url="/api/boxEsd/import"
          @success="handleUploadSuccess"
          @warning="handleUploadWarning"
          />
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <TableScrollContainer :topHeight="360">
      <template #default="{ tableHeight }">
    <el-table v-loading="loading" :data="esdList" @selection-change="handleSelectionChange" :height="tableHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="自增主键" align="center" prop="id" /> -->
      <el-table-column label="料箱编号" align="center" prop="containerId" />
      <el-table-column label="ESD 条码" align="center" prop="esdCode" />
      <el-table-column label="有效周期" align="center" prop="esdValidPeriod" />
      <el-table-column label="单位" align="center" prop="validPeriodUnit">
        <template #default="scope">
          <dict-tag :options="valid_period_unit" :value="scope.row.validPeriodUnit"/>
        </template>
      </el-table-column>
      <el-table-column label="绑定时间" align="center" prop="esdBindDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.esdBindDate) }}</span>          
          <!-- <span>{{ parseTime(scope.row.esdBindDate, '{y}-{m}-{d}') }}</span> -->
        </template>
      </el-table-column>
      <el-table-column label="ESD 条码状态" align="center" prop="esdStatus">
        <template #default="scope">
          <dict-tag :options="esd_status" :value="scope.row.esdStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="禁用状态" align="center" prop="disableStatus">
        <template #default="scope">
          <dict-tag :options="esd_disabled_status" :value="scope.row.disableStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="禁用备注" align="center" prop="disableRemark" />
      <el-table-column label="到期时间" align="center" prop="expiryDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.expiryDate) }}</span>          
          <!-- <span>{{ parseTime(scope.row.expiryDate, '{y}-{m}-{d}') }}</span> -->
        </template>
      </el-table-column>     
      <el-table-column label="剩余天数" align="center" prop="remainingDays" />       
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200" fixed="right">
        <template #default="scope">
          <!-- <el-button type="primary" icon="Cpu" @click="calculate(scope.row)">状态</el-button> -->
          <el-button type="success" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:container:edit']">修改</el-button>
          <el-button type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:container:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table> 
    <pagination
      v-show="total>0"
      :total="total"
      :page-sizes="[10, 30, 50, 100]"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
      </template>
    </TableScrollContainer>   

    <!-- 添加或修改料箱ESD信息管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" :close-on-click-modal="false">
      <el-form ref="esdRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="料箱编号" prop="containerId">
          <el-input v-model="form.containerId" placeholder="请输入料箱编号" />
        </el-form-item>
        <el-form-item label="ESD 条码" prop="esdCode">
          <el-input v-model="form.esdCode" placeholder="请输入 ESD 条码" />
        </el-form-item>
        <el-form-item label="有效周期" prop="esdValidPeriod">
          <el-input v-model="form.esdValidPeriod" placeholder="请输入有效周期" />
        </el-form-item>
        <el-form-item label="单位" prop="validPeriodUnit">
          <el-select v-model="form.validPeriodUnit" placeholder="请选择单位">
            <el-option
              v-for="dict in valid_period_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定日期" prop="esdBindDate">
          <el-date-picker 
            clearable
            v-model="form.esdBindDate"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择 ESD 绑定日期和时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="ESD 条码状态" prop="esdStatus">
          <el-select v-model="form.esdStatus" placeholder="请选择 ESD 条码状态">
            <el-option
              v-for="dict in esd_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="禁用状态" prop="disableStatus">
          <el-select v-model="form.disableStatus" placeholder="请选择禁用状态">
            <el-option
              v-for="dict in esd_disabled_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="禁用备注" prop="disableRemark">
          <el-input v-model="form.disableRemark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      title="批量新增"
      v-model="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
     >
     <el-form ref="esdRef" :model="addInfo" label-width="120px">
        <el-form-item label="ESD 条码" prop="esdCode">
          <el-input v-model="addInfo.esdCode" placeholder="请输入ESD码" />
        </el-form-item>
        <el-form-item label="有效周期" prop="esdValidPeriod">
          <el-input v-model="addInfo.esdValidPeriod" placeholder="请输入ESD有效期数值" />
        </el-form-item>
        <el-form-item label="单位" prop="validPeriodUnit">
          <el-select v-model="addInfo.validPeriodUnit" placeholder="请选择有效期单位">
            <el-option
              v-for="dict in valid_period_unit"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleAddCancel">取 消</el-button>
          <el-button type="primary" :loading="btn.batchAdd" @click="batchAdd">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="EsdMaintain">
import { listEsd, getEsd, delEsd, addEsd, updateEsd, batchAddAPI, getHeadAPI } from "@/api/work/esdMaintain"
// 新增扫码相关API
import { scanBox, bindEsd, updateBind } from "@/api/work/esdMaintain"
import TableScrollContainer from '@/components/Pagetable/TableScrollContainer.vue'

const { proxy } = getCurrentInstance()
const { esd_disabled_status, valid_period_unit, esd_status } = proxy.useDict('esd_disabled_status', 'valid_period_unit', 'esd_status')

const esdList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const dialogVisible = ref(false)
const btn = reactive({
  batchAdd: false
})  
const headInfo = ref({})

// 扫码相关变量
const scanForm = reactive({
  containerCode: '',
  esdCode: ''
})
const boxEsdStatus = ref({})
const showScanResult = ref(false)
const showUpdateInput = ref(false)

const data = reactive({
  form: {},
  addInfo: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    containerId: null,
    esdCode: null,
    esdValidPeriod: null,
    validPeriodUnit: null,
    esdBindDate: null,
    esdStatus: null,
    disableStatus: null,
    disableRemark: null,
  },
  rules: {
  }
})

const { queryParams, form, rules, addInfo } = toRefs(data)

/** 查询料箱ESD信息管理列表 */
function getList() {
  loading.value = true
  listEsd(queryParams.value).then(res => {
    if (res.errCode === '1') {
      esdList.value = res.data.page.records
      total.value = res.data.page.total
      loading.value = false
    }
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    containerId: null,
    esdCode: null,
    esdValidPeriod: null,
    validPeriodUnit: null,
    esdBindDate: null,
    esdStatus: null,
    disableStatus: null,
    disableRemark: null,
    createdBy: null,
    createTime: null,
    updatedBy: null,
    updateTime: null
  }
  proxy.resetForm("esdRef")
}

const getHead = async() => {
  const res = await getHeadAPI()
  if (res.errCode === '1') {
    headInfo.value = res.data.statistics
  }
}
getHead()

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加料箱 ESD 信息"
}

const calculate = () => {

}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getEsd(_id).then(res => {
    form.value = res.data.boxEsd
    open.value = true
    title.value = "修改料箱 ESD 信息"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["esdRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateEsd(form.value).then(res => {
          if (res.errCode === '1') {
            proxy.$modal.msgSuccess("修改成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      } else {
        addEsd(form.value).then(res => {
          if (res.errCode === '1') {
            console.log(form.value)
            proxy.$modal.msgSuccess("新增成功")
            open.value = false
            getList()
          } else {
            proxy.$modal.msgError(res.msg)
          }
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除料箱 ESD 信息管理编号为"' + _ids + '"的数据项？').then(function() {
    return delEsd(_ids)
  }).then(res => {
    if (res.errCode === '1') {
      getList()
      proxy.$modal.msgSuccess("删除成功")
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('api/boxEsd/export', {
    ...queryParams.value
  }, `ESD数据_${new Date().getTime()}.xlsx`)
}

getList()

// 下载模板
const downloadTemplate = async() => {
  proxy.download('/api/boxEsd/downloadTemplate', {}, `ESD模板_${new Date().getTime()}.xlsx`)
}
// 上传成功后的回调
const handleUploadSuccess = (res) => {
  getList()
}
// 部分成功回调
const handleUploadWarning = (res) => {
  getList()
}

const batchAddButton = () => {
  dialogVisible.value = true
}

const batchAdd = async() => {
  const _id = ids.value
  const submitForm = {
    containerId: _id,
    esdCode: addInfo.value.esdCode,
    esdValidPeriod: addInfo.value.esdValidPeriod,
    validPeriodUnit: addInfo.value.validPeriodUnit,
  }
  // console.log(submitForm)
  try {
    btn.batchAdd = true
    const res = await batchAddAPI(submitForm)
    if (res.errCode === '1') {
      dialogVisible.value = false
      getList()
      proxy.$modal.msgSuccess(res.msg)
    } else {
      proxy.$modal.msgError(res.msg)
    }
  } finally {
    btn.batchAdd = false
  }
}

const handleAddCancel = () => {
  dialogVisible.value = false
  addInfo.value = {}
}

// 扫码相关方法
/** 扫描料箱码查询状态 */
function handleScanBox() {
  if (!scanForm.containerCode) {
    proxy.$modal.msgWarning("请输入料箱码")
    return
  }
  
  scanBox(scanForm.containerCode).then(res => {
    if (res.errCode === '1') {
      boxEsdStatus.value = res.data.boxEsdStatus
      showScanResult.value = true
      showUpdateInput.value = false
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(err => {
    console.error("扫描料箱失败", err)
    proxy.$modal.msgError("扫描料箱失败")
  })
}

/** 绑定ESD（未绑定状态） */
function handleBindEsd() {
  if (!scanForm.esdCode) {
    proxy.$modal.msgWarning("请输入ESD码")
    return
  }
  
  bindEsd(scanForm.containerCode, scanForm.esdCode).then(res => {
    if (res.errCode === '1') {
      boxEsdStatus.value = res.data.boxEsdStatus
      proxy.$modal.msgSuccess("绑定成功")
      // 刷新列表数据
      getList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(err => {
    console.error("绑定ESD失败", err)
    proxy.$modal.msgError("绑定ESD失败")
  })
}

/** 更新绑定（已绑定状态） */
function handleUpdateBind() {
  if (!scanForm.esdCode) {
    proxy.$modal.msgWarning("请输入新的ESD码")
    return
  }
  
  updateBind(scanForm.containerCode, scanForm.esdCode).then(res => {
    if (res.errCode === '1') {
      boxEsdStatus.value = res.data.boxEsdStatus
      showUpdateInput.value = false
      proxy.$modal.msgSuccess("更新绑定成功")
      // 刷新列表数据
      getList()
    } else {
      proxy.$modal.msgError(res.msg)
    }
  }).catch(err => {
    console.error("更新绑定失败", err)
    proxy.$modal.msgError("更新绑定失败")
  })
}

/** 重置扫码状态 */
function resetScan() {
  scanForm.containerCode = ''
  scanForm.esdCode = ''
  boxEsdStatus.value = {}
  showScanResult.value = false
  showUpdateInput.value = false
}
</script>

<style scoped lang="scss">
:deep(.el-descriptions__title) {
  margin-bottom: 8px !important;
  font-size: large;
}

:deep(.el-descriptions__body) {
  background-color: transparent;
}

:deep(.el-descriptions__table) {
  .el-descriptions__cell {
    padding: 8px 12px !important;
  }
  
  .el-descriptions__label {
    font-weight: normal;
    color: #606266;
  }
}

.card-content {
  font-size: medium;
  // color: #ffffff;
  font-weight: bold;
  text-align: center; 
}

// 扫码区域样式
.scan-area {
  padding: 15px;
}

.scan-result-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
}

.scan-operation {
  padding: 10px 0;
}

// 状态样式
.status-expired {
  color: #F56C6C;
  font-weight: bold;
}

.status-normal {
  color: #67C23A;
  font-weight: bold;
}
</style>
